package com.nian.gateway.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.nian.common.model.Const;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
public class TokenFilter extends ZuulFilter {
    final String pre = "pre";

    @Override
    public String filterType() {
        return pre;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getParameter("token");
        log.debug("zuul token is : {}", token);
        if (StringUtils.isEmpty(token)) {
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(Const.CODE_401);
            currentContext.getResponse().setContentType(Const.HTTP_CONTENT_TYPE.JSON_UTF8);
            currentContext.setResponseBody("{\"code\":401,\"message\":\"凭证参数 Token 不存在\"}");
            return null;
        }
        /**
         * 服务端 token 验证
         */
        return null;
    }
}
